package com.weiiew.backend.utils.listener;

import lombok.RequiredArgsConstructor;
import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseInputAdapter;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author 魏锴
 * @since 2025/5/7
 */
@Component
@RequiredArgsConstructor
public class MouseSitListener extends NativeMouseInputAdapter {
    private final ListenerManager manager;
    private final AtomicBoolean isListening = new AtomicBoolean(false);
    private final Object lock = new Object(); // 添加锁对象
    private CallBack callBack = null;

    @PostConstruct
    public void init() {
        // 确保在初始化时注册监听器
        manager.registerMouseListener("firstMouseMove", this);
    }

    @PreDestroy
    public void cleanup() {
        manager.unregisterKeyListener("firstMouseMove");
    }

    public void startMouseSitListener(CallBack callBack) {
        synchronized (lock) {
            // 重置状态以避免之前的回调残留
            isListening.set(false);
            // 设置新的回调和监听状态
            this.callBack = callBack;
            isListening.set(true);
        }
    }

    @Override
    public void nativeMouseClicked(NativeMouseEvent e) {
        CallBack currentCallback = null;
        if (isListening.get()) {
            synchronized (lock) {
                if (isListening.getAndSet(false)) {
                    currentCallback = this.callBack;
                }
            }
        }
        if (currentCallback != null) {
//            System.out.println(e.getX() + " " + e.getY());
            currentCallback.callBack(e.getX(), e.getY());
        }
    }

    public interface CallBack {
        void callBack(int x, int y);
    }
}
